const db = require('../config/database')
const bcrypt = require('bcrypt')

class User {
  // 创建新用户
  static async create ({ username, email, password, nickname }) {
    try {
      // 密码加密
      const saltRounds = 10
      const passwordHash = await bcrypt.hash(password, saltRounds)

      const [result] = await db.execute(
        'INSERT INTO users (username, email, password_hash, nickname) VALUES (?, ?, ?, ?)',
        [username, email, passwordHash, nickname || username]
      )

      return {
        id: result.insertId,
        username,
        email,
        nickname: nickname || username
      }
    } catch (error) {
      throw error
    }
  }

  // 根据用户名或邮箱查找用户
  static async findByEmailOrUsername (emailOrUsername) {
    try {
      const rows = await db.query(
        'SELECT * FROM users WHERE email = ? OR username = ?',
        [emailOrUsername, emailOrUsername]
      )

      return rows[0] || null
    } catch (error) {
      throw error
    }
  }

  // 根据ID查找用户
  static async findById (id) {
    try {
      const rows = await db.query(
        'SELECT id, username, email, nickname, avatar_url, gender, birth_date, phone, bio, is_vip, vip_type, vip_expire_date, coins, created_at FROM users WHERE id = ?',
        [id]
      )

      return rows[0] || null
    } catch (error) {
      throw error
    }
  }

  // 验证密码
  static async verifyPassword (password, hashedPassword) {
    return await bcrypt.compare(password, hashedPassword)
  }

  // 更新用户信息
  static async updateById (id, updates) {
    try {
      const fields = []
      const values = []

      Object.keys(updates).forEach(key => {
        if (
          key !== 'id' &&
          key !== 'password_hash' &&
          updates[key] !== undefined
        ) {
          fields.push(`${key} = ?`)
          values.push(updates[key])
        }
      })

      if (fields.length === 0) {
        throw new Error('没有提供更新字段')
      }

      values.push(id)

      await db.query(
        `UPDATE users SET ${fields.join(', ')} WHERE id = ?`,
        values
      )

      return await this.findById(id)
    } catch (error) {
      throw error
    }
  }

  // 获取用户列表
  static async getList (page = 1, limit = 10, search = '') {
    try {
      // 确保参数是整数
      const pageNum = parseInt(page) || 1
      const limitNum = parseInt(limit) || 10
      const offset = (pageNum - 1) * limitNum

      let whereClause = ''
      let queryParams = []

      if (search) {
        whereClause = 'WHERE username LIKE ? OR email LIKE ? OR nickname LIKE ?'
        queryParams = [`%${search}%`, `%${search}%`, `%${search}%`]
      }

      // 获取总数
      const countResult = await db.query(
        `SELECT COUNT(*) as total FROM users ${whereClause}`,
        queryParams
      )

      // 获取用户列表
      const rows = await db.query(
        `SELECT id, username, email, nickname, avatar_url, gender, is_vip, 
         role, status, level, coins, last_login_time, vip_expire_date, created_at 
         FROM users ${whereClause} 
         ORDER BY created_at DESC 
         LIMIT ? OFFSET ?`,
        [...queryParams, limitNum, offset]
      )

      return {
        users: rows,
        total: countResult[0].total,
        page: pageNum,
        limit: limitNum,
        totalPages: Math.ceil(countResult[0].total / limitNum)
      }
    } catch (error) {
      throw error
    }
  }
}

module.exports = User
